<?php

// 拍卖商品管理

namespace app\console\controller;

use think\Db;
use think\Url;
use think\Loader;
use think\Request;
use think\Controller;
use app\console\model\Member as MemberModel;
use app\console\model\AuctionGoods as AuctionGoodsModel;
use app\console\model\MemberAuction as MemberAuctionModel;

class AuctionGoods extends Controller
{

    /**
     * 拍卖商品列表
     * @param $id
     * @param Request $request
     * @param AuctionGoodsModel $auctionGoods
     * @return mixed
     */
    public function index($id, Request $request, AuctionGoodsModel $auctionGoods)
    {
        // 获取参数
        $inquire = $request->param();

        // 筛选
        $condition['auction_id'] = ['eq', $id];
        if (!empty($inquire['title'])) $condition['title'] = ['like', '%' . $inquire['title'] . '%'];

        // 获取参数
        $data = $auctionGoods->where($condition)->select();


        return $this->fetch('', [
            'mate_title' => '拍卖商品列表',
            'data'       => $data,
            'auction_id' => $id
        ]);
    }


    /**
     * 新增拍卖商品
     * @param $auction_id
     * @param Request $request
     * @param AuctionGoodsModel $auctionGoods
     * @return mixed
     */
    public function create($auction_id, Request $request, AuctionGoodsModel $auctionGoods)
    {
        if ($request->isPost()) {

            // 获取参数
            $data = $request->param();

            $data['auction_id'] = $auction_id;

            $validate = Loader::validate('AuctionGoods');
            if (!$validate->check($data)) fail($validate->getError());

            // 新增数据
            $operation = $auctionGoods->allowField(true)->save($data);

            if ($operation) {
                win('操作成功', Url::build('AuctionGoods/index', ['id' => $auction_id]));
            }

            fail('操作失败');
        }


        return $this->fetch('', [
            'mate_title' => '新增拍卖商品',
        ]);
    }


    public function update($id, Request $request, AuctionGoodsModel $auctionGoods)
    {
        if ($request->isPost()) {

            // 获取参数
            $data = $request->param();


            $validate = Loader::validate('AuctionGoods');
            if (!$validate->check($data)) fail($validate->getError());

            // 新增数据
            $operation = $auctionGoods->allowField(true)->save($data,['id'=>$id]);

            if ($operation) {
                win('操作成功', Url::build('AuctionGoods/index', ['id' => $data['auction_id']]));
            }

            fail('操作失败');
        }


        $item = $auctionGoods::get($id);


        return $this->fetch('create', [
            'mate_title' => '编辑拍卖商品',
            'item'       => $item
        ]);
    }


    /**
     * 查看拍卖纪录
     */
    public function examine()
    {
        $goods_id = Request::instance()->param('id');

        $data = (new MemberAuctionModel)->with('Member')->where('goods_id', $goods_id)->paginate(12);


        return $this->fetch('', [
            'mate_title' => '拍卖纪录',
            'data'       => $data,
            'goods_id'   => $goods_id
        ]);


    }


    /**
     * 退回保证金
     */
    public function bond()
    {

        // 获取拍卖商品ID
        $goods_id = Request::instance()->param('id');

        // 查询条件
        $ini = ['goods_id' => $goods_id, 'status'   => 2,];

        // 获取保证金
        $bonds = (new AuctionGoodsModel())->where('id', $goods_id)->value('bond');

        // 获取参加拍卖的人员
        $find = (new MemberAuctionModel())->where($ini)->field('member_id,goods_id,status')->select();

        // 参加拍卖人的ID字符串
        $find_str = '';
        foreach ($find as $value) {
            $find_str .= $value['member_id'] . ',';

        }

        Db::startTrans();

        try{

            $mem_arr = [];

            // 获取参加拍卖人的ID
            $str = rtrim($find_str,',');

            //  增加余额
            Db::name('member')->where('id','in',$str)->setInc('balance',$bonds);

            // 查看用户余额
            $members = Db::name('member')->where('id','in',$str)->field('balance,id')->select();
            $new_member = [];
            foreach ($members as $value) {
                $new_member[$value['id']] = $value['balance'];
            }


            foreach ($find as $value){
                $mem_arr[] = [
                    'member_id' => $value['member_id'],
                    'type_id'   => 4,
                    'price'     => $bonds,
                    'way'       => '保证金退还',
                    'name'      => '',
                    'account'   => '',
                    'balance'   => $new_member[$value['member_id']],
                    'status'    => 1,
                    'reason'    => '',
                    'order_number' => '',
                    'create_time' => time(),
                ];
            }

            Db::name('member_withdraw')->insertAll($mem_arr);

            (new MemberAuctionModel())->where($ini)->delete();

            Db::commit();

            win('操作成功', Url::build('AuctionGoods/examine', ['id' => $goods_id]));


        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            fail('操作失败');

        }


    }


    /**
     * 生成订单号
     */
    protected function createNumber()
    {
        //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）
        $order_id_main = date('YmdHis') . rand(10000000, 99999999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
        $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);

        return $order_id;
    }
}